package gift.justflower.ecp.controller;

import gift.justflower.ecp.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.shiro.SimpleShiroToken;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutMvcContext;
import org.nutz.mvc.annotation.*;

/**
 * 基本用户控制器
 * author:AB
 * time:2018年7月17日 11:47:24
 **/
@IocBean
@At("/user")
public class UserController {
    @Inject
    private Dao dao;

    @At
    @Ok("beetl:/html/home.html")
    public void regist(@Param("..")User user){
        if(Strings.isEmpty(user.getNickname())){
            user.setNickname(user.getName());
        }
        user.setPassword(Lang.md5(user.getPassword()));
        dao.insert(user);

        Subject subject = SecurityUtils.getSubject();
        subject.login(new SimpleShiroToken(user.getName()));
        Mvcs.getHttpSession().setAttribute("user", user);
    }

    @At
    @RequiresUser
    public NutMap changePwd(@Param("password") String password, @Param("newPwd") String newPwd) {
        User user = (User) Mvcs.getHttpSession().getAttribute("user");
        NutMap nm = new NutMap("success", true);
        if (!user.getPassword().equals(Lang.md5(password))) {
            nm.setv("success", false);
        } else {
            user.setPassword(Lang.md5(newPwd));
            dao.updateIgnoreNull(user);
        }
        return nm;
    }

    @GET
    @At
    @Ok("beetl:/html/login.html")
    public void login() {
    }

    @At
    @Ok("beetl:/html/login.html")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
    }

    @At
    @POST
    @Ok(">>:/")
    public void login(@Param("..") User userIn) {
        boolean flag = true;
        User user = dao.fetch(User.class, Cnd.where("name", "=", userIn.getName()));
        if (user == null) {
            flag = false;
        }
        String hash = Lang.md5(userIn.getPassword());
        if (flag && !hash.equals(user.getPassword())) {
            flag = false;
        }
        if (flag) {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new SimpleShiroToken(user.getName()));
            Mvcs.getHttpSession().setAttribute("user", user);
        }
    }
}